<?php
/**
 * 系统设置
 * @since 1.0 <2015-5-26> SoChishun <14507247@qq.com> Added.
 */
ob_start();
include './inc/function.php';
$config = load_config();
define('MENU_CUR', '初始化数据');
msglog('====stepd_data.php====', false);
?>
<!DOCTYPE html>
<html>
    <head>
        <title><?php echo MENU_CUR ?>-INSTALL</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="skin/cssreset-min.css" rel="stylesheet" />
        <link href="skin/theme-blue.css" rel="stylesheet" />
        <script src="skin/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            // 2016-6-29
            function countdown_redirect() {
                var $dom = $('#span-countdown');
                var i = $dom.text() * 1;
                i--;
                if (i < 1) {
                    location.href = 'step_finish.php';
                }
                $dom.text(i);
            }
        </script>
    </head>
    <body class="page-step-setting">
        <?php require './inc/inc_head.php' ?>
        <div class="bodier">

            <?php
            if ('submit' == I('action')) :
                echo '<div id="message">';
                echo '<h3>执行结果：</h3>';
                ob_flush();
                flush();
                echo '<div style="max-height:150px; overflow: auto; max-width: 500px;">';
                install_data($config);
                echo '</div>';
                echo '</div>';
            else:
                ?>
                <form method="post" action="stepd_data.php" id="frmAdm">
                    <section>
                        <h3>管理员信息</h3>
                        <table cellspacing="0" class="table-form">                
                            <tr><th>管理员帐号</th><td><input type="text" name="user_name" value="<?php echo c($config, 'default_admin.user_name') ?>" placeholder="管理员帐号" required="required" /></td></tr>
                            <tr><th>管理员密码</th><td><input type="password" name="password" value="<?php echo c($config, 'default_admin.password') ?>" placeholder="管理员密码" required="required" /><a href="#" id="lnk-show-pwd">[显示]</a><span></span></td></tr> 
                            <tr><th>重复密码</th><td><input type="password" name="repassword" value="<?php echo c($config, 'default_admin.password') ?>" placeholder="重复密码" required="required" /></td></tr>
                            <tr><th>管理员Email</th><td><input type="text" name="email" value="<?php echo c($config, 'default_admin.email') ?>" placeholder="管理员Email" /><em>（用于发送程序错误报告）</em></td></tr>
                        </table>
                    </section>
                    <?php if (!empty($config['scripts']['create_data'])) { ?>
                        <section>
                            <h3>附加数据<span style="font-size:12px; margin-left:10px; font-weight:normal"><input type="checkbox" id="chk-all" style="vertical-align: middle;" />全选</span></h3>
                            <div class="checkbox-group">
                                <?php
                                $adataconf = $config['scripts']['create_data'];
                                if ($adataconf) {
                                    foreach ($adataconf as $name => $info) {
                                        echo '<span><input type="checkbox" name="data[]" value="', $name, '" />', $info['title'], '</span>';
                                    }
                                }
                                ?>
                            </div>
                        </section>
                    <?php } ?>
                    <button type="submit" style="display:none;">提交</button>
                    <input type="hidden" name="action" value="submit" />
                    <div class="footer">
                        <a href="step_finish.php" id="lnk-submit">下一步</a><a href="#" onclick="return reset_form()">重置</a>
                    </div>
                </form>
            <?php endif; ?>
        </div>
        <script type="text/javascript">
            // 2015-5-26 SoChishun Added.
            // 2016-6-14 SoChishun Refacting.
            $('#lnk-submit').click(function () {
                var opwd = {
                    pwd: $('[name="password"]').val(),
                    repwd: $('[name="repassword"]').val(),
                };
                if (opwd.pwd.length > 0 && opwd.repwd.length > 0 && opwd.pwd != opwd.repwd) {
                    alert('两次密码输入不一致!');
                    return false;
                }
                $(':submit').trigger('click');
                return false;
            })
            function reset_form() {
                document.getElementById('frmAdm').reset();
                return false;
            }
            // 全选 2016-6-20 SoChishun Added.
            $('#chk-all').click(function () {
                $('.checkbox-group input').prop('checked', $(this).prop('checked'));
            })
            $('#lnk-show-pwd').click(function () {
                var $a = $(this);
                if ($a.text() == '[隐藏]') {
                    $a.text('[显示]');
                    $a.prev().attr('type', 'password');
                } else {
                    $a.text('[隐藏]');
                    $a.prev().attr('type', 'text');
                }
                return false;
            })
        </script>
    </body>
</html>
<?php

/**
 * 
 * @param type $config
 * @return type
 * @since 2.0 2016-6-14 SoChishun Added.
 */
function install_data($config) {
    $conf_db = isset($_SESSION['suinstall-db-config']) ? $_SESSION['suinstall-db-config'] : false;
    if (!$conf_db) {
        msglog('<div class="red">数据库连接无效!</div>');
        return;
    }
    $dns = parse_dsn(array('host' => $conf_db['db_host'], 'database' => $conf_db['db_name'], 'charset' => $conf_db['charset']));
    try {
        $pdo = new PDO($dns, $conf_db['db_user'], $conf_db['db_pwd']);
    } catch (PDOException $ex) {
        msglog('<div class="red">' . $ex->getMessage() . '!</div>');
        return;
    }
    // 设置编码
    try {
        $res = $pdo->exec('SET NAMES ' . $conf_db['charset']);
    } catch (PDOException $ex) {
        msglog('<div class="red">' . $ex->getMessage() . '!</div>');
        return;
    }
    // 设置MySQL超时时间为1小时
    $pdo->exec("SET interactive_timeout = 3600;");
    $pdo->exec("SET wait_timeout = 3600;");
    // 写入管理员帐号
    if (!empty($config['scripts']['create_user'])) {
        $asqls = include MODULE_PATH . $config['scripts']['create_user'];
        if (!isset($asqls['user'])) {
            msglog('<div class="red">脚本模板[create_user]配置无效!</div>');
            return;
        }
        $adm_script = $asqls['user'];
        $admin = $_POST;
        foreach ($admin as $key => $val) {
            $adm_script = str_replace('{' . $key . '}', $val, $adm_script);
        }
        $asqls['user'] = $adm_script;
        $adm_script = '';
        try {
            foreach ($asqls as $sql) {
                if (!$sql) {
                    continue;
                }
                $res = $pdo->exec($sql);
                if (false === $res) {
                    $errorinfo = $pdo->errorInfo();
                    msglog('<div class="red">' . $errorinfo[2] . '!</div>');
                }
            }
        } catch (PDOException $ex) {
            msglog('<div class="red">' . $ex->getMessage() . '!</div>');
            return;
        }
        msglog('<div class="ok">创建管理员帐号成功!</div>');
        $_SESSION['suinstall-admin'] = $admin;
    }
    // 写入数据
    if (!empty($config['scripts']['create_data'])) {
        $datas = I('data'); // 用户勾选的体验数据项目
        $adataconf = $config['scripts']['create_data']; // 项目主要配置文件的"创建体验数据节点"内容
        if ($datas && $adataconf) {
            require './inc/ArrayToSQLHelper.php';
            $atsh = new ArrayToSQLHelper();
            foreach ($datas as $data) {
                $content_file = $adataconf[$data]['file']; // 体验数据数据源文件的地址(可以是数组)
                if (!$content_file) {
                    continue; // 无文件路径, 忽略
                }
                if (!is_array($content_file)) {
                    $content_file = array($content_file);
                }
                foreach ($content_file as $filepath) {
                    $filepath = MODULE_PATH . $filepath; // 文件路径是相对于项目配置目录的, 所以要补齐路径
                    if (file_exists($filepath)) {
                        $mode = $adataconf[$data]['mode']; // 数据内容格式
                        if ('array-data' == $mode) {
                            // 数组数据
                            $acontent = include $filepath;
                            $table = $acontent['table'];
                            $adata = $acontent['data'];
                            $is_tree = $acontent['is_tree'];
                            $asqls = $is_tree ? $atsh->generateTreeSql($table, $adata) : $atsh->generateListSql($table, $adata);
                        } else if ('array-sql' == $mode) {
                            // 数据脚本
                            $acontent = include $filepath;
                            $asqls = $acontent;
                        } else if ('sql-file' == $mode) {
                            // 文件脚本
                            $asqls = load_sql_file_to_array($filepath);
                            msglog('<div class="ok">读取文件: ' . $filepath . ' 成功!</div>');
                        }
                        patchQuery($pdo, $asqls, false, array('success' => '<div class="ok">执行命令%s...成功</div>', 'error' => '<div class="red">执行命令%s...失败</div>',));
                    }
                }
            }
            msglog('<div class="ok">写入体验数据成功!</div>');
        }
    }
    // 写入补丁
    if (!empty($config['scripts']['create_patch'])) {
        $asqls = include MODULE_PATH . $config['scripts']['create_patch'];
        patchQuery($pdo, $asqls);
        msglog('<div class="ok">写入补丁成功!</div>');
    }
    echo '<div class="ok">操作完成，即将跳转 [<span id="span-countdown">3</span>]...</div>';
    echo '<script>setInterval(countdown_redirect,1000);</script>';
    ob_flush();
    flush();
    //header('location:step_finish.php');
}
?>
    